'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import AppHeader from '@/components/ui/app-header';
import { 
  ChevronLeftIcon,
  TagIcon,
  PlusIcon,
  XMarkIcon,
} from '@heroicons/react/24/outline';
import { projectApi } from '@/lib/api';

// 定义项目类型
interface Project {
  id: string;
  name: string;
  description?: string;
}

export default function NewTaskPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const projectId = searchParams.get('projectId');
  const { data: session, status } = useSession();
  
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    status: 'TODO', // 大写状态
    priority: 'MEDIUM', // 大写优先级
    dueDate: '',
    projectId: projectId || '',
  });
  
  const [tags, setTags] = useState<string[]>([]);
  const [tagInput, setTagInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [projects, setProjects] = useState<Project[]>([]);
  const [projectsLoading, setProjectsLoading] = useState(true);

  // 获取用户项目列表
  useEffect(() => {
    async function fetchProjects() {
      if (status !== 'authenticated') return;
      
      setProjectsLoading(true);
      try {
        const projectsList = await projectApi.getProjects();
        setProjects(Array.isArray(projectsList) ? projectsList : []);
      } catch (err) {
        console.error('获取项目列表失败:', err);
      } finally {
        setProjectsLoading(false);
      }
    }

    fetchProjects();
  }, [status]);

  // 处理表单字段变更
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 处理标签添加
  const handleAddTag = () => {
    if (tagInput.trim() && !tags.includes(tagInput.trim())) {
      setTags(prev => [...prev, tagInput.trim()]);
      setTagInput('');
    }
  };

  // 处理标签删除
  const handleRemoveTag = (tagToRemove: string) => {
    setTags(prev => prev.filter(tag => tag !== tagToRemove));
  };

  // 处理标签输入框按键事件
  const handleTagKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddTag();
    }
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/task', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...formData,
          tags,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || `请求失败: ${response.status}`);
      }

      const data = await response.json();
      if (data.success) {
        // 创建成功，跳转到任务详情页
        router.push(`/task/${data.data.id}`);
      } else {
        throw new Error(data.message || '创建任务失败');
      }
    } catch (err: any) {
      console.error('创建任务失败:', err);
      setError(err.message || '创建任务失败');
    } finally {
      setLoading(false);
    }
  };

  // 检查用户是否已登录
  if (status === 'loading') {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-pulse text-gray-500">加载中...</div>
      </div>
    );
  }

  if (status === 'unauthenticated') {
    router.push('/auth/login');
    return null;
  }

  return (
    <div className="min-h-screen">
      <main className="py-6 px-4 sm:px-6 lg:px-8 max-w-7xl mx-auto">
        <div className="mb-6">
          <button
            type="button"
            onClick={() => router.back()}
            className="inline-flex items-center px-3 py-1 border border-transparent text-sm font-medium rounded-md text-gray-700 hover:bg-gray-100 focus:outline-none"
          >
            <ChevronLeftIcon className="h-5 w-5 mr-1" />
            返回
          </button>
        </div>

        <AppHeader
          title="创建新任务"
          subtitle={projectId ? "为当前项目添加新任务" : "创建一个新任务"}
        />

        <div className="mt-6 bg-white shadow rounded-lg overflow-hidden">
          <form onSubmit={handleSubmit} className="p-6">
            {error && (
              <div className="mb-6 bg-red-50 p-4 rounded-md">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <XMarkIcon className="h-5 w-5 text-red-400" aria-hidden="true" />
                  </div>
                  <div className="ml-3">
                    <h3 className="text-sm font-medium text-red-800">创建任务时出错</h3>
                    <div className="mt-2 text-sm text-red-700">
                      <p>{error}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}

            <div className="space-y-6">
              {/* 任务标题 */}
              <div>
                <label htmlFor="title" className="block text-sm font-medium text-gray-700">
                  任务标题 <span className="text-red-500">*</span>
                </label>
                <div className="mt-1">
                  <input
                    type="text"
                    name="title"
                    id="title"
                    required
                    value={formData.title}
                    onChange={handleChange}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                    placeholder="输入任务标题"
                  />
                </div>
              </div>

              {/* 任务描述 */}
              <div>
                <label htmlFor="description" className="block text-sm font-medium text-gray-700">
                  任务描述
                </label>
                <div className="mt-1">
                  <textarea
                    name="description"
                    id="description"
                    rows={4}
                    value={formData.description}
                    onChange={handleChange}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                    placeholder="详细描述任务内容、要求等"
                  />
                </div>
              </div>

              {/* 项目选择 */}
              <div>
                <label htmlFor="projectId" className="block text-sm font-medium text-gray-700">
                  所属项目 <span className="text-red-500">*</span>
                </label>
                <div className="mt-1">
                  {projectsLoading ? (
                    <div className="animate-pulse h-10 bg-gray-100 rounded-md"></div>
                  ) : (
                    <select
                    name="projectId"
                    id="projectId"
                    required
                    value={formData.projectId}
                    onChange={handleChange}
                    disabled={!!projectId}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm disabled:bg-gray-100"
                    >
                      <option value="">选择项目</option>
                      {projects.map(project => (
                        <option key={project.id} value={project.id}>
                          {project.name}
                        </option>
                      ))}
                    </select>
                  )}
                </div>
                {projectId ? (
                  <p className="mt-1 text-xs text-gray-500">项目ID已从URL参数中获取</p>
                ) : projects.length === 0 && !projectsLoading ? (
                  <p className="mt-1 text-xs text-red-500">
                    未找到可用项目，请先<a href="/project/new" className="underline text-blue-500">创建一个项目</a>
                </p>
                ) : null}
              </div>

              {/* 任务状态 */}
              <div>
                <label htmlFor="status" className="block text-sm font-medium text-gray-700">
                  任务状态
                </label>
                <div className="mt-1">
                  <select
                    id="status"
                    name="status"
                    value={formData.status}
                    onChange={handleChange}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="TODO">待处理</option>
                    <option value="IN_PROGRESS">进行中</option>
                    <option value="REVIEW">审核中</option>
                    <option value="DONE">已完成</option>
                  </select>
                </div>
              </div>

              {/* 优先级 */}
              <div>
                <label htmlFor="priority" className="block text-sm font-medium text-gray-700">
                  优先级
                </label>
                <div className="mt-1">
                  <select
                    id="priority"
                    name="priority"
                    value={formData.priority}
                    onChange={handleChange}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  >
                    <option value="LOW">低</option>
                    <option value="MEDIUM">中</option>
                    <option value="HIGH">高</option>
                    <option value="URGENT">紧急</option>
                  </select>
                </div>
              </div>

              {/* 截止日期 */}
              <div>
                <label htmlFor="dueDate" className="block text-sm font-medium text-gray-700">
                  截止日期
                </label>
                <div className="mt-1">
                  <input
                    type="date"
                    name="dueDate"
                    id="dueDate"
                    value={formData.dueDate}
                    onChange={handleChange}
                    className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                  />
                </div>
              </div>

              {/* 标签 */}
              <div>
                <label htmlFor="tags" className="block text-sm font-medium text-gray-700">
                  标签
                </label>
                <div className="mt-1 flex rounded-md shadow-sm">
                  <div className="relative flex flex-grow items-stretch focus-within:z-10">
                    <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                      <TagIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                    </div>
                    <input
                      type="text"
                      id="tags"
                      value={tagInput}
                      onChange={(e) => setTagInput(e.target.value)}
                      onKeyDown={handleTagKeyDown}
                      className="block w-full rounded-none rounded-l-md border-gray-300 pl-10 focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
                      placeholder="添加标签"
                    />
                  </div>
                  <button
                    type="button"
                    onClick={handleAddTag}
                    className="relative -ml-px inline-flex items-center space-x-2 rounded-r-md border border-gray-300 bg-gray-50 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
                  >
                    <PlusIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />
                    <span>添加</span>
                  </button>
                </div>

                {tags.length > 0 && (
                  <div className="mt-2 flex flex-wrap gap-2">
                    {tags.map((tag) => (
                      <span
                        key={tag}
                        className="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800"
                      >
                        {tag}
                        <button
                          type="button"
                          onClick={() => handleRemoveTag(tag)}
                          className="ml-1 inline-flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full text-blue-400 hover:bg-blue-200 hover:text-blue-500 focus:bg-blue-500 focus:text-white focus:outline-none"
                        >
                          <span className="sr-only">移除标签 {tag}</span>
                          <XMarkIcon className="h-3 w-3" aria-hidden="true" />
                        </button>
                      </span>
                    ))}
                  </div>
                )}
              </div>

              {/* 提交按钮 */}
              <div className="flex justify-end pt-5">
                <button
                  type="button"
                  onClick={() => router.back()}
                  className="rounded-md border border-gray-300 bg-white py-2 px-4 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                >
                  取消
                </button>
                <button
                  type="submit"
                  disabled={loading || !formData.title || !formData.projectId}
                  className="ml-3 inline-flex justify-center rounded-md border border-transparent bg-[var(--primary-color)] py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-[var(--primary-hover)] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50"
                >
                  {loading ? '创建中...' : '创建任务'}
                </button>
              </div>
            </div>
          </form>
        </div>
      </main>
    </div>
  );
} 